package cz.muni.fi.hauntedhousesweb.web;

import cz.muni.fi.hauntedhouses.service.HumanService;
import cz.muni.fi.hauntedhouses.to.HumanTO;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

/**
 *
 * @author Martin Vala, 359917
 */
@UrlBinding("/humans/{$event}/{human.id}")
public class HumansActionBean implements ActionBean {

    private ActionBeanContext context;
    
    @SpringBean
    private HumanService humanService;
    
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }
    
    @DefaultHandler
    public Resolution all() {
        return new ForwardResolution("/showHumans.jsp");
    }
    
    public List<HumanTO> getHumans() {
        return humanService.findAll();
    }
    
    @ValidateNestedProperties(value = {
    @Validate(on = {"add", "save"}, field = "name", required = true),
    @Validate(on = {"add", "save"}, field = "gender", required = true)
    })
    
    private HumanTO human; 
    
    public Resolution add() {
        humanService.create(human);
        return new RedirectResolution(this.getClass(), "all");
    }

    public HumanTO getHuman() {
        return human;
    }

    public void setHuman(HumanTO human) {
        this.human = human;
    }
    
    public Resolution delete() {
        humanService.remove(human);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void loadBookFromDatabase() {
        String ids = context.getRequest().getParameter("human.id");
        if (ids != null) {
            human = humanService.get(Long.parseLong(ids));
        }
    }
 
    public Resolution edit() {
        return new ForwardResolution("/editHuman.jsp");
    }
 
    public Resolution save() {
        humanService.update(human);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution cancel() {
        return new RedirectResolution(this.getClass(), "all");
    }
    
}
